from service.setting_service import DataDictionaryService
from views.common.translator import Translator
from views.template_page_view import BasePageTemplateView, FormItemDto
from common.utils.utils_log import AntLogger
from views.template.data_classes import TableDataDto, ComponentConfig
from PyQt6.QtWidgets import QHeaderView, QSizePolicy


class CommonSettingView(BasePageTemplateView):

    def __init__(self, parent=None):
        t = Translator()
        super().__init__("CommonSettingView", parent=parent)
        self.dataMapService = DataDictionaryService()
        self.searchKey = ""

    def doInitAndUpdate(self):
        # 添加搜索和操作按钮
        self._add_top_operation()
        
        # 添加设置表单
        self._add_setting_form()
        
        # 添加设置表格
        self._add_setting_table()

    def _add_top_operation(self):
        """添加顶部搜索和操作按钮"""
        # 定义组件配置列表
        components = [
            ComponentConfig(
                component_type="QLineEdit",
                callback=self.search_settings,
                kwargs={"placeholder": "输入关键字搜索设置"}
            ),
            ComponentConfig(
                component_type="PushButton",
                callback=self.add_new_setting,
                kwargs={"text": "新增设置", "width": 100}
            ),
            ComponentConfig(
                component_type="PushButton",
                callback=self.refresh_data,
                kwargs={"text": "刷新数据", "width": 100}
            )
        ]
        
        # 添加顶部操作栏
        self.addTopOperation(
            title="设置操作",
            component_configs=components,
            datParamFun=lambda: self.getBaseParam(),
            style_file="form_style.qss"
        )

    def _add_setting_form(self):
        """添加设置表单"""
        AntLogger.info("加载Setting页面")

        form_items = self.dataMapService.get_all_common_settings()

        # 使用样式文件创建表单
        form_result = self.addFromTemplate(
            form_items=form_items, 
            title="基础配置表单", 
            callback=self.commonSettingCallback
        )
        
        # 使用封装方法应用样式
        self.apply_style_to_widget(form_result, "form_style.qss")

    def _add_setting_table(self):
        """添加设置表格"""
        # 添加表格
        table_result = self.addTableTemplate(
            title="系统设置列表",
            dataFun=self.get_settings_table_data,
            datParamFun=lambda: self.getBaseParam(),
            stretch=1,  # 设置stretch为1，使表格能够在垂直方向上拉伸
            style_file="table_style.qss"
        )
        
        # 应用样式
        self.apply_style_to_widget(table_result, "table_style.qss")
        
        # 设置表格自适应大小
        if hasattr(table_result.inner, "tableWidget") and table_result.inner.tableWidget:
            # 设置表格列宽自适应内容
            table_result.inner.tableWidget.horizontalHeader().setSectionResizeMode(
                QHeaderView.ResizeMode.ResizeToContents
            )
            # 设置最后一列自动填充剩余空间
            table_result.inner.tableWidget.horizontalHeader().setStretchLastSection(True)
            # 设置表格自动填充可用空间
            table_result.inner.tableWidget.setSizePolicy(
                QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding
            )

    def commonSettingCallback(self, form_data: list[FormItemDto]):
        """处理表单提交"""
        AntLogger.info(f"Form Data: {form_data}")
        """
        接收 FormItemDto 列表并保存到数据库。
        """

        for item in form_data:
            # 调用 DataDictionaryService 的保存方法
            try:
                self.dataMapService.save_or_update_common_setting(
                    item.form_key, item.form_value, item.form_desc
                )
                AntLogger.info(
                    f"Saved field: {item.form_key} - {item.form_value}")
            except Exception as e:
                AntLogger.info(
                    f"Failed to save field {item.form_key}. Error: {e}")
        
        # 刷新表格数据
        self.refreshAllData()

    def get_settings_table_data(self, param_dict=None) -> TableDataDto:
        """获取设置表格数据"""
        try:
            # 从数据库获取所有设置
            settings = self.dataMapService._setting_das.get_all_settings()
            
            # 定义表头
            headers = ["ID", "键名", "值", "描述", "创建时间", "更新时间", "操作"]
            
            # 准备表格数据
            data = []
            for setting in settings:
                # 搜索过滤
                if param_dict and isinstance(param_dict, dict) and "search_key" in param_dict and param_dict["search_key"]:
                    search_key = param_dict["search_key"].lower()
                    if (search_key not in setting.setting_key.lower() and 
                        (not setting.setting_desc or search_key not in setting.setting_desc.lower()) and
                        (not setting.setting_value or search_key not in setting.setting_value.lower())):
                        continue
                
                # 格式化日期时间
                created_at = setting.created_at.strftime("%Y-%m-%d %H:%M:%S") if setting.created_at else ""
                updated_at = setting.updated_at.strftime("%Y-%m-%d %H:%M:%S") if setting.updated_at else ""
                
                # 添加行数据
                data.append([
                    str(setting.id),
                    setting.setting_key,
                    setting.setting_value or "",
                    setting.setting_desc or "",
                    created_at,
                    updated_at,
                    setting.setting_key  # 用于操作按钮的标识
                ])
            
            # 定义操作按钮
            operations = [
                {"编辑": self.edit_setting},
                {"删除": self.delete_setting}
            ]
            
            return TableDataDto(table_header=headers, table_data=data, table_item_fun=operations)
        
        except Exception as e:
            AntLogger.error(f"获取设置表格数据失败: {e}")
            import traceback
            AntLogger.error(traceback.format_exc())
            # 返回空表格
            return TableDataDto(
                table_header=["ID", "键名", "值", "描述", "创建时间", "更新时间", "操作"],
                table_data=[],
                table_item_fun=[{"编辑": self.edit_setting}, {"删除": self.delete_setting}]
            )

    def getBaseParam(self):
        """获取基本参数"""
        return {"search_key": self.searchKey if hasattr(self, 'searchKey') else ""}

    def search_settings(self, search_text):
        """搜索设置"""
        self.searchKey = search_text
        self.refreshDataForTemplate("系统设置列表")
        return "搜索成功"

    def add_new_setting(self):
        """添加新设置"""
        # 定义表单配置
        form_config = [
            {"type": "text", "label": "键名", "name": "key", "required": True},
            {"type": "text", "label": "值", "name": "value"},
            {"type": "text", "label": "描述", "name": "desc"}
        ]
        
        # 添加自定义表单
        self.addCustomBox(
            title="新增设置",
            form_config=form_config,
            on_submit=self._handle_add_setting,
            style_file="form_style.qss"
        )
        
        return "打开新增设置表单"

    def _handle_add_setting(self, form_data):
        """处理新增设置表单提交"""
        try:
            key = form_data.get("key", "")
            value = form_data.get("value", "")
            desc = form_data.get("desc", "")
            
            if not key:
                return "键名不能为空"
            
            # 保存设置
            self.dataMapService.save_or_update_common_setting(key, value, desc)
            
            # 刷新所有数据，包括表单和表格
            self.refreshAllData()
            
            return "设置添加成功"
        except Exception as e:
            AntLogger.error(f"添加设置失败: {e}")
            return f"添加设置失败: {str(e)}"

    def edit_setting(self, key):
        """编辑设置"""
        try:
            # 获取设置
            setting = self.dataMapService._setting_das.get_setting_by_key(key)
            if not setting:
                return f"未找到键为 {key} 的设置"
            
            # 定义表单配置
            form_config = [
                {"type": "hidden", "name": "key", "value": setting.setting_key},
                {"type": "text", "label": "键名", "name": "key_display", "value": setting.setting_key, "disabled": True},
                {"type": "text", "label": "值", "name": "value", "value": setting.setting_value or ""},
                {"type": "text", "label": "描述", "name": "desc", "value": setting.setting_desc or ""}
            ]
            
            # 添加自定义表单
            self.addCustomBox(
                title=f"编辑设置: {setting.setting_key}",
                form_config=form_config,
                on_submit=self._handle_edit_setting,
                style_file="form_style.qss"
            )
            
            return "打开编辑设置表单"
        except Exception as e:
            AntLogger.error(f"打开编辑设置表单失败: {e}")
            return f"打开编辑设置表单失败: {str(e)}"

    def _handle_edit_setting(self, form_data):
        """处理编辑设置表单提交"""
        try:
            key = form_data.get("key", "")
            value = form_data.get("value", "")
            desc = form_data.get("desc", "")
            
            if not key:
                return "键名不能为空"
            
            # 更新设置
            self.dataMapService.save_or_update_common_setting(key, value, desc)
            
            # 刷新所有数据，包括表单和表格
            self.refreshAllData()
            
            return "设置更新成功"
        except Exception as e:
            AntLogger.error(f"更新设置失败: {e}")
            return f"更新设置失败: {str(e)}"

    def delete_setting(self, key):
        """删除设置"""
        try:
            # 删除设置
            success = self.dataMapService.delete_setting(key)
            
            # 刷新所有数据，包括表单和表格
            self.refreshAllData()
            
            if success:
                return f"设置 {key} 已删除"
            else:
                return f"删除设置 {key} 失败"
        except Exception as e:
            AntLogger.error(f"删除设置失败: {e}")
            return f"删除设置失败: {str(e)}"

    def refresh_data(self):
        """刷新数据"""
        self.refreshAllData()
        return "数据已刷新"
